package com.gks.itcast.hr_user_consumer_2_8001.hanlder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;


@ControllerAdvice
public class ControllerExceptionHandler {
    @Autowired
    private RedisTemplate redisTemplate;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final String SENDFLAG="send";


    @Autowired
    JavaMailSender sender ;

    @Value("${spring.mail.username}")
    private String from ;


    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHander(HttpServletRequest request, Exception e) throws Exception {
        logger.error("Requst URL : {}，Exception : {}", request.getRequestURL(),e);

        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
            throw e;
        }

        ModelAndView mv = new ModelAndView();
        mv.addObject("url",request.getRequestURL());
        mv.addObject("exception", e);
        mv.setViewName("error/error");
        String sendInof = (String) redisTemplate.opsForValue().get(SENDFLAG);
        if(sendInof==null){
            redisTemplate.opsForValue().set(SENDFLAG,"发送短信控制",300L, TimeUnit.SECONDS);
            new Thread(()->{
                //        添加紧急通知(采用邮箱的形式发送异常信息):
                SimpleMailMessage mail = new SimpleMailMessage() ;
                //设置发送者
                mail.setFrom(from);
                mail.setTo("3268761517@qq.com");
                mail.setSubject("代码异常紧急通知");
                mail.setText(request.getRequestURI()+"接口出现异常,异常信息如下:  "+e+"  请立刻进行修复!!!");

                //抄送
                //mail.setCc(cc);

                sender.send(mail);
            }).start();


        }




        return mv;
    }
}
